# -*- encoding: utf-8 -*-
import os
from datetime import datetime
import tempfile
import contextlib
import json


os.environ.update([
    ('NLS_LANG', 'SIMPLIFIED CHINESE_CHINA.UTF8'),
    ('ORA_NCHAR_LITERAL_REPLACE', 'TRUE')
])
import cx_Oracle as cxo
import sqlalchemy

from . import utils


def get_config(cfg_file=None):
    '''读取数据库连接配置'''
    if cfg_file is  None:
        cfg_file = os.path.join(os.getcwd(),  'config.json')
    return json.load(open(cfg_file, 'r'))

def get_connection(cfg_file=None):
    '''取得数据库连接'''
    cfg = get_config(cfg_file)
    username = cfg.get('username', 'sys')
    password = cfg.get('password', None)
    host = cfg.get('host', '127.0.0.1')
    port = cfg.get('port', 1521)
    service_name = cfg.get('service_name', 'XE')
    conn_str = '{0}:{1}/{2}'.format(host, port, service_name)
    return cxo.connect(username, password, conn_str)

def get_sqlalchemy_uri(cfg_file=None):
    '''取得用于sqlalchemy连接的uri'''
    cfg = get_config(cfg_file)
    username = cfg.get('username', 'sys')
    password = cfg.get('password', None)
    host = cfg.get('host', '127.0.0.1')
    port = cfg.get('port', 1521)
    service_name = cfg.get('service_name', 'XE')
    dsn_str = cxo.makedsn(host, port, service_name=service_name)
    return 'oracle+cx_oracle://{0}:{1}@{2}'.format(username, password, dsn_str)

def get_sqlalchemy_engine(cfg_file=None, echo=False):
    uri = get_sqlalchemy_uri(cfg_file)
    return sqlalchemy.create_engine(uri, echo=echo)

def touch(fname):
    open(fname, 'a').close()
    os.utime(fname, None)

def query_total_count(connection, sql):
    '''获取查询的sql语句会返回的数据总条数'''
    total = 0
    sql_count = '''
    SELECT COUNT(*) AS total_row
    FROM (
        {0}
    )
    '''.format(sql)
    with contextlib.closing(connection.cursor()) as cursor:
        cursor.execute(sql_count)
        row = cursor.fetchone()
        if isinstance(row, tuple) and len(row) == 1:
            total = row[0]
    return total